package com.hethongviet.vending.helper.adapter;

import java.io.InputStream;
import java.util.List;

import com.hethongviet.vending.R;
import com.hethongviet.vending.model.BoxItem;
import com.hethongviet.vending.model.Product;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListItemProductAdapter extends ArrayAdapter<BoxItem> {
	private final List<BoxItem> values;
	private final Activity activity;

	/* Make higher performance */
	private static class ViewHolder {
		public TextView _textProductName;
		public TextView _textProductPrice;
		public ImageView _imageProduct;
	}

	public ListItemProductAdapter(Activity activity, List<BoxItem> values) {
		super(activity, R.layout.list_item_product, values);
		this.values = values;
		this.activity = activity;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		final ViewHolder viewHolder;

		if (rowView == null) {
			LayoutInflater layoutInflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = layoutInflater.inflate(R.layout.list_item_product,
					parent, false);
			viewHolder = new ViewHolder();
			viewHolder._textProductName = (TextView) rowView
					.findViewById(R.id.text_product_name);
			viewHolder._textProductPrice = (TextView) rowView
					.findViewById(R.id.text_product_price);
			viewHolder._imageProduct = (ImageView) rowView
					.findViewById(R.id.image_product);
			rowView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) rowView.getTag();
		}
		/* Initiate items */
		final BoxItem currentProductItem = values.get(position);
		Product currentProduct = currentProductItem.getProduct();
		String name = currentProduct.getName();
		int maxStringLeng = 14;
		if (name != null && name.length() > maxStringLeng)
			viewHolder._textProductName.setText((name).substring(0,
					maxStringLeng - 2) + "...");
		else
			viewHolder._textProductName.setText(name);

		viewHolder._textProductPrice.setText("" + currentProduct.getPrice());
		
		InputStream inputStream = null;
		try {
			inputStream = activity.getAssets().open(
					"products/" + currentProduct.getCode() + ".png");
		} catch (Exception e) {
			e.printStackTrace();
			inputStream = null;
		}

		if (inputStream != null) {
			// Bitmap bitmap = AppMain.getInstance().decodeFile(new
			// File(AppMain.getInstance().DIRECTORY_IMAGE
			// + currentProduct.getImageName()));

			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			viewHolder._imageProduct.setImageBitmap(bitmap);
		}
		/* Return view */
		return rowView;
	}
}
